// 酷贝M24SR04演示代码
// 使用了stm32duino/STM32duino M24SR64-Y

#include <cupeM24SR.h>
#include <M24SR.h>
#include <Wire.h>

#define M24SR_ADDR 0xAC
TwoWire dev_i2c(M24_SDA, M24_SCL);
M24SR nfcTag(M24SR_ADDR, &dev_i2c, NULL, M24_INT, M24_RF_CS);

const char *title[] = {"Length system file", "I²C protect", "I²C watchdog", "GPO", "ST reserved", "RF enable", "NDEF File number (RFU)", "UID", "Memory Size", "Product Code"};
// 显示系统配置文件
void dump_system_file(uint8_t *data)
{
  dbLog("\n\nConfiguration of the M24SR04\n");
  for(int i = 0; i < 10; i++) {
    if(i != 0 && i != 7 && i != 8 ){
      dbLog("\n%s: %02X", title[i], *data);
      data++;
    } else {
      if(i != 7){
        dbLog("\n%s: %02X", title[i], *data);
        data++;
        dbLog(" %02X", *data);
        data++;
      }
      else{
        dbLog("\n%s: ", title[i]);
        for(int j = 0; j < 7; j++) {
          dbLog("%02X ", *data);
          data++;
        }
      }
    }
  }
  dbLog("\n");
}

void CupeM24SR::init()
{
  const char text_write[] = "Hello M24SR04! I can control you now!"; // Text to write in the tag
  char text_read[255] = {'\0'}; // Text read in the tag

  dev_i2c.begin();

  dbLog("\nInitialize M24SR device: 0x%04X", nfcTag.begin(NULL));

  // 退出RF模式，否则后面的操作会失败
  dbLog("\nAbort RF connection: 0x%04X", nfcTag.force_get_session());

  dbLog("\nSelect the application file: 0x%04X", nfcTag.select_application());

  dbLog("\nSelect the system file: 0x%04X", nfcTag.select_system_file());

  uint8_t data[18];
  memset(data, 0, sizeof(data));
  dbLog("\nRead system configuration: 0x%04X", nfcTag.read_binary(0, 18, data));
  dump_system_file(data);

  // 不关闭I2C保护，后面的操作会失败(你拿到手的酷贝是开启了I2C保护的)
  // dbLog("\nPassword Verify: 0x%04X", nfcTag.verify(nfcTag.I2CPwd, 0x10, nfcTag.DEFAULT_PASSWORD));
  // uint8_t i2c_protect = 0x00;
  // dbLog("\nDisable Protect: 0x%04X", nfcTag.update_binary(0x02, 1, (uint8_t*)&i2c_protect));

  dbLog("\nWrite: %s", nfcTag.writeTxt(text_write) ? "Success" : "Failed");

  delay(100);

  nfcTag.readTxt(text_read);
  dbLog("\nMessage content: %s", text_read);

  if(strcmp(text_write, text_read) == 0) {
    dbLog("\nSuccessfully written and read!");
  } else {
    dbLog("\nRead failed!");
  }
}

void CupeM24SR::loop()
{
}
